package com.atmilan.quartz.job;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

import com.atmilan.quartz.constant.Constants;
import com.atmilan.quartz.constant.enums.SyncStatusEnum;
import com.atmilan.quartz.model.entity.crmeb.SystemConfig;
import com.atmilan.quartz.service.ISystemConfigService;
import com.atmilan.quartz.sync.push.crmeb.service.ICrmebService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xxl.job.core.handler.annotation.XxlJob;

import lombok.extern.slf4j.Slf4j;

/**
 * 阿里图搜服务
 * @Description: 
 * @author daigb
 * @date 2021-04-13
 */
@Slf4j
@Configuration
@EnableScheduling
public class SeachImageTask {
	@Autowired
    BaseTask baseTask;
    @Autowired
    ICrmebService crmebService;
    @Autowired
    ISystemConfigService systemConfigService;

    /**
     * 30分钟图像搜索服务
     * 
     */
    @XxlJob("seachImageTask")
    public void tusouTask() {
        try {
            // 查询任务
            SystemConfig systemConfig = systemConfigService.getOne(Wrappers.<SystemConfig>lambdaQuery()
                    .eq(SystemConfig::getName, Constants.TUSOU_SYNC_STATUS)
                    .last("LIMIT 1")
                    );
            SyncStatusEnum buyerSyncStatus = SyncStatusEnum.valueOf(systemConfig.getFormId());
//            long timeDiff = new Date().getTime() - systemConfig.getUpdateTime().getTime();

            log.warn("--------------- 开始图搜服务, 同步状态为: {} ---------------", buyerSyncStatus);
            // 72小时内状态还未变更, 直接重新处理
            /*if (SyncStatusEnum.WAIT == buyerSyncStatus && 72 < (timeDiff / 1000 / 60 / 60)) {
                log.warn("--------------- 图搜服务过程超过72小时, 自动重新启动服务 ---------------");
                buyerSyncStatus = SyncStatusEnum.PUSH;
            }*/
            // 有同步任务时不进行处理
            if (SyncStatusEnum.WAIT == buyerSyncStatus) {
                log.warn("--------------- 图搜任务未结束, 新任务不执行 ---------------");
                return;
            }
            // 更新任务状态为同步中
            updateSeachSyscStatus(Constants.TUSOU_SYNC_STATUS, SyncStatusEnum.WAIT, systemConfig);
            boolean b = crmebService.seachImageTask();
            if(b) {
                updateSeachSyscStatus(Constants.TUSOU_SYNC_STATUS, SyncStatusEnum.PUSH, systemConfig);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private void updateSeachSyscStatus(String name, SyncStatusEnum value, SystemConfig systemConfig) {
        systemConfigService.update(Wrappers.<SystemConfig>lambdaUpdate()
                .eq(SystemConfig::getName, name)
                .set(SystemConfig::getFormId, value)
                .set(SystemConfig::getUpdateTime, new Date()));
        log.warn("--------------- config: {}状态改变为: {} ---------------", name, value.getMsg());
    }
}
